package io.renren.modules.com.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import io.renren.modules.com.entity.ComImageEntity;
import io.renren.modules.com.service.ComImageService;

/**
 * 
 * 
 * @author pfp
 * @email
 * @date 2017-07-16 09:34:53
 */
@Controller
@RequestMapping("comimage")
public class ComImageController {
	@Autowired
	private ComImageService comImageService;

	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@ResponseBody
	@RequiresPermissions("comimage:list")
	public R list(@RequestParam Map<String, Object> params) {
		// 查询列表数据
		Query query = new Query(params);

		List<ComImageEntity> comImageList = comImageService.queryList(query);
		int total = comImageService.queryTotal(query);

		PageUtils pageUtil = new PageUtils(comImageList, total, query.getLimit(), query.getPage());

		return R.ok().put("page", pageUtil);
	}

	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public R delete(@RequestBody Long[] imageIds) {
		comImageService.deleteBatch(imageIds);
		return R.ok();
	}

	/**
	 * 上传文件
	 */
	@RequestMapping("/upload")
	@ResponseBody
	public R upload(@RequestParam("file") MultipartFile file) throws Exception {
		if (file.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}

		Long imageId = comImageService.upload(file);
		if (imageId != null) {
			return R.ok().put("imageId", imageId);
		}
		return R.error("上传失败");
	}

	@RequestMapping("/getPhoto")
	@ResponseBody
	public R getPhoto(@RequestParam("imageId") Long imageId, HttpServletResponse response) throws Exception {
		if (imageId == null) {
			throw new RRException("文件号不能为空");
		}

		String imageStr = comImageService.getPhoto(imageId);
		return R.ok().put("imageStr", imageStr);
	}

}
